package com.example.network;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class NetManager
{
	HashMap<Integer, Request> requestHash;
	Object lock;
	public static final int POST_TIMES = 5;
	
	private NetManager()
	{
		requestHash = new HashMap<Integer, Request>();
		lock = new Object();
	}
	
	static final String tag = "NetManager";
	
	public static NetManager getManager()
	{
		return new NetManager();
	}
	
	Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			TempOb yop = (TempOb) msg.obj;
			yop.ob.notifyError(yop.r.getType(), Const.NO_NETWORK, "无网络连接");
		}
	};
	
	public class TempOb
	{
		NetObserver ob;
		Request r;
	}
	
	public void excute(final Request r, final NetObserver ob, Context context)
	{
		if (ob == null)
		{
			throw new RuntimeException(" ob is null ");
		}
		if (!getNetWorkStatus(context))
		{
			handler.postDelayed(new Runnable()
			{
				@Override
				public void run()
				{
					Message message = new Message();
					TempOb ab = new TempOb();
					ab.ob = ob;
					ab.r = r;
					message.obj = ab;
					handler.sendMessage(message);
				}
			}, 2000);
			// ob.notifyError(r.getType(), Const.NO_NETWORK, "没有网络");
			return;
		}
		synchronized (lock)
		{
			if (requestHash.containsKey(r.getType()))
			{
				ob.rePost(r);
				return;
			}
			else
			{
				requestHash.put(r.getType(), r);
			}
		}
		NetTask task = new NetTask(ob, r);
		task.execute();
	}
	
	@SuppressWarnings("unused")
	private class NetTask extends AsyncTask<Void, Integer, Void>
	{
		NetObserver ob;
		Request r;
		
		public NetTask(NetObserver ob, Request r)
		{
			this.ob = ob;
			this.r = r;
		}
		@Override
		protected Void doInBackground(Void... arg0)
		{
			String result = "";
			for (int i = 0; i < POST_TIMES; i++)
			{
				result = r.getAction().postToService();
				if (result != null && !result.equals(""))
				{
					r.getResponse().setResult(result);
					break;
				}
			}
			if (result == null || result.equals(""))
			{
				publishProgress(Const.NO_NETWORK);
				synchronized (lock)
				{
					requestHash.remove(r.getType());
				}
			}
			else
			{
				try
				{
					Log.e("result", "===============" + result);
					JSONObject object = new JSONObject(result);
					String result2 = object.getString("result");
					JSONObject object2 = new JSONObject(result2);
					int code = object2.getInt("code");
					if (code == Const.SUCCESS)
					{
						r.getResponse().setOnlyReposon(object);
					}
					else
					{
						if (object2.has("message"))
						{
							String error = object2.getString("message");
							r.setErrorMsg(error);
						}
					}
					publishProgress(code);
				}
				catch (JSONException e)
				{
					publishProgress(Const.SERVER_DATA_FORMAT_ERROR);
				}
				synchronized (lock)
				{
					requestHash.remove(r.getType());
				}
			}
			return null;
		}
		@Override
		protected void onProgressUpdate(Integer... values)
		{
			super.onProgressUpdate(values);
			int code = values[0];
			if (code == Const.SUCCESS)
			{
				ob.getResult(r);
			}
			else
			{
				ob.notifyError(r.getType(), code, r.getErrorMsg());
			}
		}
	}
	
	public static boolean getNetWorkStatus(Context context)
	{
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manager.getActiveNetworkInfo();
		if (info == null)
		{
			return false;
		}
		return info.isAvailable();
	}
}
